<template>
  <div class="task-board">
    <!-- 操作区 -->
    <el-card shadow="never" class="mb-4">
      <el-button type="success" size="small" @click="openAddDialog">新增工单</el-button>
      <el-input v-model="searchKey" placeholder="搜索工单编号/产品/客户" clearable size="small" style="width:200px;margin-left:16px"/>
    </el-card>
    <!-- 看板区 -->
    <div class="kanban-columns">
      <div v-for="(list, status) in lists" :key="status" class="kanban-col">
        <div class="col-header">{{ columnTitles[status] }}</div>
        <draggable
          v-model="lists[status]"
          :group="'orders'"
          :animation="200"
          item-key="orderNo"
          @end="handleDragEnd"
        >
          <template #item="{element}">
            <el-card class="kanban-card" shadow="hover">
              <div class="flex justify-between items-center">
                <div>
                  <div class="font-bold">{{ element.productName }}</div>
                  <div class="text-xs text-gray-500">{{ element.orderNo }}</div>
                </div>
                <el-tag size="small" :type="tagType(status)">{{ columnTitles[status] }}</el-tag>
              </div>
              <div class="mt-2">
                <div class="text-xs"><b>客户：</b>{{ element.customer }}</div>
                <div class="text-xs"><b>开工：</b>{{ element.startDate }}</div>
              </div>
              <div class="kanban-actions">
                <el-button size="small" @click="openEditDialog(element)">编辑</el-button>
                <el-button size="small" type="danger" @click="removeOrder(element)">删除</el-button>
              </div>
            </el-card>
          </template>
        </draggable>
      </div>
    </div>
    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogMode==='add' ? '新增工单' : '编辑工单'" v-model="showDialog" width="400px">
      <el-form :model="dialogForm" label-width="80px" :rules="dialogRules" ref="dialogFormRef">
        <el-form-item label="工单编号" prop="orderNo">
          <el-input v-model="dialogForm.orderNo" :disabled="dialogMode==='edit'" />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="dialogForm.productName" />
        </el-form-item>
        <el-form-item label="客户" prop="customer">
          <el-input v-model="dialogForm.customer" />
        </el-form-item>
        <el-form-item label="开工时间" prop="startDate">
          <el-date-picker v-model="dialogForm.startDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width:100%"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="submitDialog">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, nextTick } from 'vue'
import draggable from 'vuedraggable'
import { ElMessage } from 'element-plus'

// 看板列定义
const columnTitles = {
  pending: '待开始',
  processing: '进行中',
  finished: '已完成'
}
const tagType = s => s === 'pending' ? 'info' : (s === 'processing' ? 'success' : 'warning')

// 模拟初始数据（15条分3列）
const allOrders = ref(generateMockOrders())
function generateMockOrders() {
  const process = ['头孢胶囊','维C片','葡萄糖注射液','布洛芬片','阿莫西林颗粒']
  const cust = ['新华医药','仁和药业','复星医药','哈药集团']
  return Array.from({length:15}).map((_,i) => {
    let status
    if (i<5) status='pending'
    else if(i<10) status='processing'
    else status='finished'
    return {
      orderNo: `GD20250${i+1}`,
      productName: process[i%5],
      customer: cust[i%4],
      startDate: `2025-06-${String(i+1).padStart(2,'0')}`,
      status
    }
  })
}

// 拆分为看板列
const lists = reactive({
  pending: [],
  processing: [],
  finished: []
})

function updateLists() {
  lists.pending = allOrders.value.filter(o=>o.status==='pending')
  lists.processing = allOrders.value.filter(o=>o.status==='processing')
  lists.finished = allOrders.value.filter(o=>o.status==='finished')
}
updateLists()

// 拖拽结束
function handleDragEnd(evt) {
  // 拖动后同步allOrders的status
  Object.entries(lists).forEach(([status, arr]) => {
    arr.forEach(item => {
      const origin = allOrders.value.find(o => o.orderNo === item.orderNo)
      if(origin) origin.status = status
    })
  })
  updateLists()
  ElMessage.success('状态已变更')
}

// 搜索
const searchKey = ref('')
watchEffect(() => {
  if(!searchKey.value){
    updateLists()
    return
  }
  const key = searchKey.value.trim()
  lists.pending = allOrders.value.filter(o=>o.status==='pending' && (
    o.orderNo.includes(key) || o.productName.includes(key) || o.customer.includes(key)))
  lists.processing = allOrders.value.filter(o=>o.status==='processing' && (
    o.orderNo.includes(key) || o.productName.includes(key) || o.customer.includes(key)))
  lists.finished = allOrders.value.filter(o=>o.status==='finished' && (
    o.orderNo.includes(key) || o.productName.includes(key) || o.customer.includes(key)))
})

// --- 增删改 ---
const showDialog = ref(false)
const dialogMode = ref('add') // add/edit
const dialogForm = reactive({
  orderNo: '',
  productName: '',
  customer: '',
  startDate: ''
})
const dialogFormRef = ref()
const dialogRules = {
  orderNo: [{ required: true, message: '必填', trigger: 'blur' }],
  productName: [{ required: true, message: '必填', trigger: 'blur' }],
  customer: [{ required: true, message: '必填', trigger: 'blur' }],
  startDate: [{ required: true, message: '必填', trigger: 'blur' }]
}
let editingOrderNo = ''

function openAddDialog() {
  dialogMode.value = 'add'
  Object.assign(dialogForm, {orderNo:'',productName:'',customer:'',startDate:''})
  showDialog.value = true
  nextTick(()=>dialogFormRef.value && dialogFormRef.value.clearValidate())
}
function openEditDialog(row) {
  dialogMode.value = 'edit'
  Object.assign(dialogForm, {...row})
  editingOrderNo = row.orderNo
  showDialog.value = true
  nextTick(()=>dialogFormRef.value && dialogFormRef.value.clearValidate())
}
function submitDialog() {
  dialogFormRef.value.validate(valid => {
    if(!valid) return
    if(dialogMode.value==='add'){
      allOrders.value.unshift({
        ...dialogForm,
        status:'pending'
      })
      ElMessage.success('新增成功')
    }else{
      // 编辑
      const item = allOrders.value.find(o=>o.orderNo===editingOrderNo)
      if(item){
        Object.assign(item, dialogForm)
        ElMessage.success('编辑成功')
      }
    }
    showDialog.value = false
    updateLists()
  })
}
function removeOrder(row) {
  allOrders.value = allOrders.value.filter(o=>o.orderNo !== row.orderNo)
  updateLists()
  ElMessage.success('删除成功')
}
</script>

<style scoped>
.task-board {
  padding: 20px 16px;
}
.mb-4 {
  margin-bottom: 16px;
}
.kanban-columns {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}
.kanban-col {
  background: #f7fafc;
  border-radius: 12px;
  flex: 1 1 0;
  min-width: 280px;
  min-height: 400px;
  padding: 12px 8px;
  box-shadow: 0 1px 4px #0001;
  display: flex;
  flex-direction: column;
}
.col-header {
  font-weight: bold;
  text-align: center;
  margin-bottom: 10px;
  letter-spacing: 2px;
}
.kanban-card {
  margin-bottom: 14px;
  border-radius: 10px;
  transition: box-shadow .2s;
}
.kanban-card:last-child { margin-bottom:0; }
.kanban-actions {
  margin-top: 8px;
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}
</style>
